from django.db import models
from django.db.models.query import QuerySet
from django.utils import timezone 
from django.contrib.auth.models import User 
from django.urls import reverse
from taggit.managers import TaggableManager

# Create your models here.
#自定义模型管理器
class PublishedManager(models.Manager):
  def get_queryset(self) :
    return super(PublishedManager,
    self).get_queryset().filter(status='published')
#文章数据模型
class Post(models.Model):
  objects = models.Manager(),
  published = PublishedManager()   
  STATUS_CHOICES = ( 
    ('draft', 'Draft'),
    ('published', 'Published'),
  ) 
  # 增加tags字段 标签属性
  tags = TaggableManager()
  title = models.CharField(max_length=250) 
  body = models.TextField() 
  slug = models.SlugField(max_length=250, unique_for_date='publish') 
  #作者
  author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') 
  #发布时间
  publish = models.DateTimeField(default=timezone.now) 
  #创建时间
  created = models.DateTimeField(auto_now_add=True) 
  #更新时间
  updated = models.DateTimeField(auto_now=True) 
  #状态
  status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') 

  class Meta: 
    ordering = ('-publish',) 
  def __str__(self): 
    return self.title 
  def get_absolute_url(self): 
    return reverse('blog:post_detail', args=[self.publish.year, 
                  self.publish.month, self.publish.day, self.slug])  
#评论模型
class Comment(models.Model): 
  post = models.ForeignKey(Post, 
            on_delete=models.CASCADE, 
            related_name='comments') 
  name = models.CharField(max_length=80) 
  email = models.EmailField() 
  body = models.TextField() 
  created = models.DateTimeField(auto_now_add=True) 
  updated = models.DateTimeField(auto_now=True) 
  active = models.BooleanField(default=True) 
  class Meta: 
    ordering = ('created',) 
  def __str__(self): 
    return f'Comment by {self.name} on {self.post}'
